﻿using Avalonia.Platform.Storage;
using DX.IO;
using System;
using System.IO;

namespace DX
{
    class AvaloniaFileEntry : FileEntry
    {

        public AvaloniaFileEntry(IStorageFile storageFile) : base(storageFile.Path.AbsolutePath)
        {
            this.storageFile = storageFile;

        }
        private readonly IStorageFile storageFile;
        Stream stream;

        public override byte[] GetBuffer()
        {
            using var newstream = OpenRead();
            byte[] buffer = new byte[newstream.Length];
            newstream.ReadExactly(buffer, 0, buffer.Length);
            return buffer;
        }

        public override Stream OpenRead()
        {
            if (stream != null) throw new FileEntryException("File is Open");
            stream = storageFile.OpenReadAsync().GetAwaiter().GetResult();
            return stream;
        }

        public override Stream OpenWrite()
        {
            if (stream != null) throw new FileEntryException("File is Open");
            stream = storageFile.OpenWriteAsync().GetAwaiter().GetResult();
            return stream;
        }
        protected override void OnDispose( )
        {
          
            if (stream != null)
            {
                stream.Dispose();
                stream = null;
            }
        }
    }
}
